/*
 * @Author: lucina
 * @Date: 2024-01-25 21:30:30
 * @Description: 项目公共函数
 */
/**
 * @Author: lucina
 * @description: 资源上传
 * @param {*} config 配置参数
 */
export async function upload(config={url:'',params:'',imageListName:'',_this:{},event:{},limitType:'',fileMaxSize:1 * 1024 * 1024,maxSize:20 * 1024 * 1024,fileMinSize:5 * 1024,list:[]}){
	return new Promise(async(resolve, reject) => {
		let { list } = config
		for (let index in list) {
			const item = list[index];
			const fileSize = item.size;
			const fileName = item.url ?? '';
			// console.log(event)
			if (!isAssetTypeAnImage(item.url,config.limitType)) {
				config._this.$dialog.toast('不允许该文件类型上传')
				return false
			}
			console.log('文件大小', fileSize);
			// console.log('文件大小', this.fileMaxSize);

			if (fileSize > config.fileMaxSize) {
				console.log('开始压缩')
				const compressionRatio = getCompressionRatio(fileSize,config.fileMaxSize);
				if (compressionRatio > 1) {
					config._this.$dialog.toast(`文件不能大于10M`)
					return false
				}
				// 超出1M自动压缩图片
				 // const imgRes = await mpImageCompress.set(item.url, 1024) // 1024K
				// console.info(imgRes)
				console.log('',item.size)
				let { url,size } = await compressMedia({
					source:item,compressionRatio,_this:config._this
				})
				item.url = url
				item.size = size
				item.thumb = url
				console.log('压缩后的路径',list[index])

				if (item.size > config.maxSize) {
					config._this.$dialog.toast(`文件压缩后超出`)
					return false
				}
			}
			console.log('查看大小',item.size,config.fileMinSize)
			if (item.size < config.fileMinSize) {
				config._this.$dialog.toast(`文件不能小于5KB`)
				return false
			}


			config._this[`fileList`].push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
			console.log('大小--',config._this[`fileList`])
		}
		for (let i = 0; i < list.length; i++) {
			const result = await uploadFilePromise({
				params:config.params,
				filePath:list[i].url
			}); //调用上传图片的方法



			if (result.code != 200) {
				// console.log(result)
				// uni.showMsg(result.Message);
				const index = config._this[config.imageListName].findIndex(event => config.event.name === list[i].name)
				if (index !== -1) return config._this[config.imageListName].splice(index, 1);
			}
			// 垃圾回收
			// window.URL.revokeObjectURL(list[i].url);
			let item = config._this[`fileList`][config.fileListLen]
			config._this[`fileList`].splice(config.fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: `${ uni.$http.mediaUrl }${ result?.data }`,
				res: `${ uni.$http.mediaUrl }${ result?.data }` || list[i].url
			}))
			config.fileListLen++

		}
	})
}
/**
 * @Author: lucina
 * @description:
 * @param {*} config
 * @param {*} params
 */
export function compressMedia(config={source:'',compressionRatio:'',_this:{}}){
	return new Promise((resolve, reject) => {
		let { url,type } = config.source
		uni.compressImage({
			src: url,
			quality:config?.compressionRatio,
			success: (res) => {
				 uni.getFileInfo({ //可以看压缩后的大小留着
				   filePath:res.tempFilePath,
				   success:(item)=> {
					   resolve({
					   	size:item.size,
					   	url:res.tempFilePath
					   });
				   },
				   fail:() => {
					   resolve({
					   	size:'',
					   	url:res.tempFilePath
					   });
				   }
			   })

				console.log('图片压缩成功', res)
			},
			fail: (err) => {
				reject(err)
				console.log('图片压缩失败', err)
			}
		})
	})
}
/**
 * @Author: lixiang
 * @description: 上传回调
 * @param {*} url
 */
export function uploadFilePromise(config={params:{},filePath:'',uploadUrl:`${uni.$http.baseUrl}fileUpload/`}) {
	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: config?.uploadUrl || `${uni.$http.baseUrl}fileUpload/`, // 仅为示例，非真实的接口地址
			filePath: config.filePath,
			name: 'myfile',
			formData: {
				...config.params
			},
			success: (res) => {
				// var meta = JSON.parse(res.data);
				// this.imagelist.push(meta.url)
				// self.imagecheck = false
				setTimeout(() => {
					resolve(JSON.parse(res.data))
				}, 1000)
			}
		});
	})
}
/**
 * @Author: lucina
 * @description: 检测判断文件类型是否正确
 * @param {*} ext
 */
export function isAssetTypeAnImage(ext,limitType) {
	const str = ext.split('.')[1];
	return limitType.indexOf(str.toLowerCase()) !== -1;
}
/**
 * @Author: lucina
 * @description: 获取文件大小倍数，生成质量比
 * @param {*} fileSize
 */
export function getCompressionRatio(fileSize,fileMaxSize) {
	const multiple = (fileSize / fileMaxSize).toFixed(2);
	return multiple > 5 ? 0.5 : multiple > 4 ? 0.6 : multiple > 3 ? 0.7 : multiple > 2 ? 0.8 : multiple > 1 ? 0.9 : 2;
}
/**
 * 图片压缩
 * imgSrc 地址
 * scale 压缩质量 0-1
 * type 文件类型
 */
const compressImg= (imgSrc, scale, type, callback)  =>   {
	// uni.$u.toast('压缩中')
	var img = new Image();
	img.src = imgSrc;
	img.onload = function() {
		var that = this;
		var h = (img.height * scale).toFixed(0); // 默认按质量比例压缩
		var w = (img.width * scale).toFixed(0);
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var width = document.createAttribute("width");
		width.nodeValue = w;
		var height = document.createAttribute("height");
		height.nodeValue = h;
		canvas.setAttributeNode(width);
		canvas.setAttributeNode(height);
		ctx.drawImage(that, 0, 0, w, h);
		var base64 = canvas.toDataURL('image/jpeg', scale); //压缩比例
		canvas = null;
		if (type == 'base64') {
			let data = {
				size: getBase64Size(base64),
				type: type,
				source: base64
			}
			callback(base64);
		} else {
			let blob = base64ToBlob(base64);
			console.log('压缩后的大小', blob.size);
			const blobUrl = window.URL.createObjectURL(blob); //blob地址
			blob.source = blobUrl
			callback(blob);
		}
	}
};
/**base转Blob */
const base64ToBlob = (base64) => {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
};
/**获取base64的文件大小 */
const getBase64Size = () => {
	let size = 0;
	if (base64Str) { // 获取base64图片byte大小
		const equalIndex = base64Str.indexOf('='); // 获取=号下标
		if (equalIndex > 0) {
			const str = base64Str.substring(0, equalIndex); // 去除=号
			const strLength = str.length;
			const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
			size = Math.floor(fileLength); // 向下取整
		} else {
			const strLength = base64Str.length;
			const fileLength = strLength - (strLength / 8) * 2;
			size = Math.floor(fileLength); // 向下取整
		}
	} else {
		size = null;
	}
	return size
};

export function formatProductName (name){
	if (name.length > 10) {
		// 如果名字超过6个字符，只保留前6个字符并最后加上"..."
		return name.slice(0,10 ) + '...';
	} else {
		// 否则直接返回原名
		return name;
	}
}
export function formatProducDetail (name){
	if (name.length > 10) {
		// 如果名字超过6个字符，只保留前6个字符并最后加上"..."
		return name.slice(0, 10) + '...';
	} else {
		// 否则直接返回原名
		return name;
	}
}